package com.pro01.backend.utils;

public class UrlUtil {

    /*
    public static String urlDecodeHex(String encoded) {
        try {
            byte[] bytes = new byte[encoded.length()];
            int byteCount = 0;
            for (int i = 0; i < encoded.length(); ) {
                if (encoded.charAt(i) == '%') {
                    String hex = encoded.substring(i + 1, i + 3);
                    bytes[byteCount++] = (byte) Integer.parseInt(hex, 16);
                    i += 3;
                } else {
                    bytes[byteCount++] = (byte) encoded.charAt(i);
                    i++;
                }
            }
            return bytesToHex(bytes, byteCount);
        } catch (Exception e) {
            return null;
        }
    }
     */

    public static String urlDecodeHex(String encoded) {
        try {
            // 将 URL 编码转成 byte[]
            byte[] bytes = new byte[20]; // info_hash 是 20 字节
            int byteCount = 0;
            for (int i = 0; i < encoded.length(); ) {
                if (encoded.charAt(i) == '%') {
                    String hex = encoded.substring(i + 1, i + 3);
                    bytes[byteCount++] = (byte) Integer.parseInt(hex, 16);
                    i += 3;
                } else {
                    bytes[byteCount++] = (byte) encoded.charAt(i);
                    i++;
                }
            }

            // 转换为 40 位的十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < byteCount; i++) {
                sb.append(String.format("%02x", bytes[i] & 0xff));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    private static String bytesToHex(byte[] bytes, int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(String.format("%02x", bytes[i] & 0xff));
        }
        return sb.toString().toUpperCase();
    }
}
